﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DBLOG.BizTalk.BizTalkExplorerServices.Entities;
using Microsoft.BizTalk.ExplorerOM;
using DBLOG.BizTalk.BizTalkExplorerServices.Core;

namespace DBLOG.BizTalk.BizTalkExplorerServices.Entities
{
    public class BTSApplication : BTSEntityBase
    {
        private Application _application { get; set; }

        public List<BTSSendPort> SendPorts { get; set; }

        public List<BTSReceivePort> ReceivePorts { get; set; }

        public List<BTSOrchestration> Orchestrations { get; set; }

        public BizTalkApplicationState State { get; set; }

        public BTSApplication()
        {
        }

        internal BTSApplication(Application application)
        {
            this._application = application;

            this.PopulateSimpleProperties();

            this.PopulateSendPorts();

            this.PopulateReceivePorts();

            this.PopulateOrchestrations();
        }

        private void PopulateSimpleProperties()
        {
            this.Name = this._application.Name;

            this.Details = this._application.Description;

            switch (this._application.Status)
            {
                case Microsoft.BizTalk.ExplorerOM.Status.Stopped:
                    this.State = BizTalkApplicationState.Stopped;
                    break;
                case Microsoft.BizTalk.ExplorerOM.Status.PartiallyStarted:
                    this.State = BizTalkApplicationState.PartiallyStarted;
                    break;
                case Microsoft.BizTalk.ExplorerOM.Status.Started:
                    this.State = BizTalkApplicationState.Started;
                    break;
            }
        }

        private void PopulateSendPorts()
        {
            var sendPorts = from s in this._application.SendPorts.Cast<SendPort>().ToList<SendPort>()
                            select new BTSSendPort(s);

            this.SendPorts = sendPorts.ToList<BTSSendPort>();
        }

        private void PopulateReceivePorts()
        {
            var receivePorts = from r in this._application.ReceivePorts.Cast<ReceivePort>().ToList<ReceivePort>()
                               select new BTSReceivePort(r);

            this.ReceivePorts = receivePorts.ToList<BTSReceivePort>();
        }

        private void PopulateOrchestrations()
        {
            var orchestrations = from o in this._application.Orchestrations.Cast<BtsOrchestration>().ToList<BtsOrchestration>()
                                 select new BTSOrchestration(o);

            this.Orchestrations = orchestrations.ToList<BTSOrchestration>();
        }
    }

    public enum BizTalkApplicationState
    {
        Stopped=0, PartiallyStarted=1, Started=2
    }
}
